﻿using Rbac.Domain.Entity;
using Rbac.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rbac.Domain.Impl
{
	public class PermissionRepository:IPermissionRepository
	{
		private readonly RbacContext db;
		public PermissionRepository(RbacContext db)
		{
			this.db = db;
		}
		/// <summary>
		/// 权限添加
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		/// <exception cref="NotImplementedException"></exception>
		public int Add(Permission entity)
		{
			db.Permissions.Add(entity);
			return db.SaveChanges();
		}
		/// <summary>
		/// 权限删除
		/// </summary>
		/// <param name="idList"></param>
		/// <returns></returns>
		/// <exception cref="NotImplementedException"></exception>
		public int Delete(int loginUserId,params int[] idList)
		{
			if(idList.Length <= 0)
			{
				return 0;
			}
			var peimiss = db.Permissions.Where(c => idList.Contains(c.PermissionId));
			foreach(var item in peimiss)
			{
				item.IsDeleted= true;
				item.UpdatedTime = DateTime.Now;
				item.UpdatedUserId = loginUserId;
			}
			return db.SaveChanges();
		}
		/// <summary>
		/// 获取查询权限
		/// </summary>
		/// <param name="pName"></param>
		/// <returns></returns>
		/// <exception cref="NotImplementedException"></exception>
		public List<Permission> GetPermissions(string pName)
		{
			var list = db.Permissions.Where(c => c.IsDeleted == false);
			if(!string.IsNullOrWhiteSpace(pName))
			{
				list = list.Where(c => c.PermissionName.StartsWith(pName));
			}
			return list.ToList();
		}
		/// <summary>
		/// 权限修改
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		/// <exception cref="NotImplementedException"></exception>
		public int Update(Permission entity)
		{
			var permiss=db.Permissions.FirstOrDefault(c=>c.PermissionId==entity.PermissionId);
			permiss.PermissionName= entity.PermissionName;
			permiss.PermissionUrl= entity.PermissionUrl;
			permiss.Remark= entity.Remark;
		    permiss.UpdatedTime = DateTime.Now;
			return db.SaveChanges();
		}
		/// <summary>
		/// 判断是否有权限
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public bool HasPermission(int roleId,string controllerName, string actionName)
		{
			var permission = db.Permissions.FirstOrDefault(c => c.ControllerName.ToLower() .Contains(controllerName.ToLower()) && c.ActionName.ToLower().Contains(actionName.ToLower()));
			if(permission == null)
			{
				return false;
			}
			//判断角色表中有没有记录
			var result = db.RolePermissions.FirstOrDefault(c => c.RoleId == roleId && c.PermissionId == permission.PermissionId);
			return result != null;
		}
	}
}
